﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Core
{
    public class MessageHandlerInstanceSystem : EntitySystem, IAwake
    {
        public Dictionary<Type, IMessageHandler> handlers = new Dictionary<Type, IMessageHandler>();

        public void Awake()
        {
            Subscribe<AnalysisHandlerAssembly>(AnalysisHandlerAssembly);
            Subscribe<HandleMessage>(HandleMessage);
        }

        private void AnalysisHandlerAssembly(ref AnalysisHandlerAssembly data)
        {
            var allTypes = data.handlerAssembly.GetTypes();
            foreach (var currentType in allTypes)
            {
                if (currentType.IsAbstract)
                    continue;

                if (!currentType.IsDefined(typeof(MessageHandlerAttribute)))
                    continue;

                var handlerSystem = Activator.CreateInstance(currentType) as IMessageHandler;
                var messageType = handlerSystem.GetRequestType();

                if (handlers.ContainsKey(messageType))
                {
                    new CoreTip(TipLevel.Error, $"There are already exist the same type message {messageType.FullName}").Publish();
                    continue;
                }

                handlers[messageType] = handlerSystem;
            }
        }

        private void HandleMessage(ref HandleMessage eventData)
        {
            if (!handlers.TryGetValue(eventData.message.GetType(), out var handler))
            {
                new CoreTip($"找不到消息处理器：{eventData.message.GetType()}, sessionID:{eventData.session.SessionID}").Publish();
                return;
            }

            handler.OnReceive(eventData.session, eventData.message, eventData.rpcID);
        }
    }

    public struct AnalysisHandlerAssembly : IEventData
    {
        public Assembly handlerAssembly;

        public AnalysisHandlerAssembly(Assembly handlerAssembly)
        {
            this.handlerAssembly = handlerAssembly;
        }
    }
}
